package com.lxw.report.meta.config.shiro;

/**
 * shiro配置类
 */

import cn.hutool.core.codec.Base64;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /**
     * 安全管理配置
      * @param sessionManager
     * @param ehCacheManager
     * @return
     */
    @Bean("securityManager")
    public SecurityManager securityManager(UserRealm userRealm,SessionManager sessionManager,EhCacheManager ehCacheManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 自定义缓存实现
        securityManager.setCacheManager(ehCacheManager);

        // 设置cookie管理
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        // rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)
        cookieRememberMeManager.setCipherKey(Base64.decode("liuxiongweibaoyaling=="));
        securityManager.setRememberMeManager(cookieRememberMeManager);

        //认证配置
        securityManager.setRealm(userRealm);

        //session配置
        securityManager.setSessionManager(sessionManager);

        return securityManager;
    }



    /**
     * session配置
     *
     * @return sessionManager
     */
    @Bean("sessionManager")
    public SessionManager sessionManager(EhCacheManager ehCacheManager,RedisTemplate<Object, Object> template) {
        //默认设置内存sessionDao
        ShiroSessionManager sessionManager = new ShiroSessionManager();
        //会话验证调度器
        sessionManager.setSessionValidationSchedulerEnabled(true);
        // 去掉 JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        // 删除过期的session
        sessionManager.setDeleteInvalidSessions(true);
        // 全局session生命周期 (毫秒)
        sessionManager.setGlobalSessionTimeout(8 * 60 * 60 * 1000);
        //设置session的缓存方式,如果设置缓存则优先从缓存中读取，读不到则从sessionDao中读取
        sessionManager.setCacheManager(ehCacheManager);
        //设置自定义sessionDao替换默认的memorySessionDao
        sessionManager.setSessionDAO(new RedisSessionDAO(template));
        return sessionManager;
    }

    /**
     * ehCacheManager缓存配置
     * @return
     */
    @Bean("ehCacheManager")
    public EhCacheManager ehCacheManager() {
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
        cacheManager.init();
        //防止项目重启多线程创建缓存导致重复错误，此处先创建session缓存
        //默认缓存名称
        String cacheName=CachingSessionDAO.ACTIVE_SESSION_CACHE_NAME;
        cacheManager.getCache(cacheName);
        return cacheManager;
    }

    /**
     * redis缓存配置
     * @return
     */
    public ShiroRedisCacheManager cacheManager(RedisTemplate template) {
        return new ShiroRedisCacheManager(template);
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        //注册user自定义过滤器
        Map<String, Filter> filters = new LinkedHashMap<>();
        filters.put("user", new ShiroUserFilter());
        shiroFilter.setFilters(filters);

        //设置过滤规则
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/login", "anon");
        filterMap.put("/favicon.ico", "anon");
        //下面4个为swagger使用
        filterMap.put("/swagger-ui/**", "anon");
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/v2/api-docs/**", "anon");
        /**
         * 此处设置为用户级别，后续若有安全问题提升为authc
         */
        filterMap.put("/**", "user");
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

    /**
     * 保证实现Shiro内部lifecycle函数的bean执行
     * @return
     */
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * setUsePrefix(true)用于解决一个奇怪的bug。在引入spring aop的情况下。
     * 在@Controller注解的类的方法中加入@RequiresRole等shiro注解，会导致该方法无法映射请求，导致返回404。
     * 加入这项配置能解决这个bug
     */
    @Bean
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }

}
